import scheduler, time, InterfaceExt, userPref, InterfaceRB, Xml, os, MonthlyCleanup
from time import strptime, strftime

def checkTimeOfModification():
    """Check the time of last modification of each file and launch backup if necessary"""
    
    timeOfLastBackup = retrieveAllXml('C:\\Program Files\\EasyBackupTool\\BackupTimes.xml')
    listTempFilesToBackup=[]
    for el in retrieveAllXml('C:\\Program Files\\EasyBackupTool\\backupFile.xml'):
        if os.path.getmtime(os.path.normpath(el)) > timeOfLastBackup[0]:
            listTempFilesToBackup.append(os.path.normpath(el))
    createXml('C:\\Program Files\\EasyBackupTool\\tempFilesToBackup.xml','FilesToBackup',listTempFilesToBackup)
    InterfaceExt.Backup()
    list=[]
    list.append(time.strftime("%d-%m-%Y@%Hh%Mm%Ss"))
    Xml.createXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-LastBackup.xml', 'lastbackuptime',list)
    res = InterfaceRB.checkTreshold(userPref.get('DiskCleanupTreshold'))
    if res != 'NULL':
        if userPref.get('DiskCleanupAuto') == 'OFF':
            print res
        else:
            diskCleanupMCleanup()
            res = InterfaceRB.checkTreshold(userPref.get('DiskCleanupTreshold'))
            if res != 'NULL':
                print res
            
def diskCleanupMCleanup():
    """Make a MCleanup of all files on backupDir from beginning till Month(now)-1"""
    
    dateBegin = getFirstLaunch()
    yearBegin = strptime(dateBegin, "%Y")
    monthBegin = strptime(dateBegin, "%m")
    monthEnd = time.strftime("%m")
    yearEnd = time.strftime("%Y")
    
#    if month != '1':
#        monthEnd=str(int(monthEnd)-1)
#    else:
#        monthEnd='12'
#        yearEnd=str(int(yearEnd)-1)
        
    for elements in range(int(monthBegin),13):
        MonthlyCleanup.MonthlyCleanup(str(elements), yearEnd)
    for element in range(int()+1,int(yearEnd)):
        for zelem in range(1,13):
            MonthlyCleanup.MonthlyCleanup(str(zelem), str(element))
    for elem in range(1, monthEnd):
        MonthlyCleanup.MonthlyCleanup(str(elem))
    
        
def getFirstLaunch():
    """return date of overall first backup"""
    
    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(list[0])
    #dategiven = strptime(date, "%d-%m-%Y@%Hh%Mm%Ss")
    result='NULL'
    temp = strptime('31-12-2999@23h59m59s', "%d-%m-%Y@%Hh%Mm%Ss")
    for elements in listBackup:
            value = elements.split('.')
            dateCheck = elements.split('_')
            if ((value[-1]=='acl')or(value[-1]=='xdelta')):
                dateval = dateCheck[-1].split('.')
                a = strptime(dateval[0], "%d-%m-%Y@%Hh%Mm%Ss")
                if (a < temp):
                    temp=a
    result = strftime("%d-%m-%Y@%Hh%Mm%Ss", temp)
    return result

if __name__ == "__main__":
    #print getFirstLaunch()
    runtime = time.localtime(time.time() + int(userPref.getValue('BackupInterval')))
    command = '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\DynamicScheduling.py"'
#    scheduler.create_task('EBT-DailyDynamic', command, 'OnceDynamic')
    checkTimeOfModification()